﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Transactions;
using Newtonsoft.Json;
using System.Reflection;
using System.Data;
using T.ServiceComponent.DAC.Service;
using T.ServiceComponent.DataAccessEx.Core;
using T.FAS.Runtime.Base.Common;
using T.FAS.Runtime.Base.Entity;
using T.ServiceComponent.I18N.Service;

namespace T.FAS.Runtime.Base.Dao
{
    public class QueryPlanDao : DaoService<QueryPlan>
    {
        private static readonly object _lock = new object();
        public override string TableName => "FAS_QueryPlan";
        public override string IDColumnName => "ID";
        public QueryPlanDao() : base()
        {
            DBName = "TFAS";
        }
        public override List<string> ExceptColumnName => new List<string> {
            "IsAuth",
            "ShareUsers",
            "FilterContent",
            "FilterShow",
            "SortContent",
            "ColumnContent",
            "CrossColumn",
            "ListViewSet",
            "ChartViewSet",
            "PivotViewSet",
            "TreeViewSet",
            "CardViewSet",
            "UseColumnContent",
            "TopTime",
            "IsChartChange",
            "Charts",
            "WarningID",
            "OriginalContentID",
            "DefaultPortalId",
            nameof(QueryPlan.PortalId),
            nameof(QueryPlan.PortalFilterContent),
        };
        public override Dictionary<string, object> GetDataMapping(QueryPlan data)
        {
            var datas = base.GetDataMapping(data);
            datas.Remove("PlanRange");
            datas.Add("PlanRange", (int)(data.PlanRange));
            datas.Remove("DefaultView");
            datas.Add("DefaultView", (int)(data.DefaultView));
            datas.Remove(nameof(QueryPlan.PlanType));
            datas.Add(nameof(QueryPlan.PlanType), (int)(data.PlanType));
            return datas;
        }
        public override QueryPlan ConvertToObject(Dictionary<string, PropertyInfo> columns, DataRow row)
        {
            var myCol = new Dictionary<string, PropertyInfo>(base.Columns);
            myCol.Remove("PlanRange");
            myCol.Remove("DefaultView");
            myCol.Remove("TopTime");
            myCol.Remove(nameof(QueryPlan.PlanType));
            var data = base.ConvertToObject(myCol, row);
            if (row["PlanRange"] != DBNull.Value)
                data.PlanRange = (PlanRange)Enum.Parse(typeof(PlanRange), Convert.ToString(row["PlanRange"]));
            else
                data.PlanRange = PlanRange.Private;
            if (row["DefaultView"] != DBNull.Value)
                data.DefaultView = (ViewType)Enum.Parse(typeof(ViewType), Convert.ToString(row["DefaultView"]));
            if (row[nameof(QueryPlan.PlanType)] != DBNull.Value)
                data.PlanType = (PlanType)Enum.Parse(typeof(PlanType), Convert.ToString(row[nameof(QueryPlan.PlanType)]));
            else
                data.PlanType = PlanType.QueryPlan;
            return data;
        }
        #region 1.0版本方案，弃用
        /// <summary>
        /// 更改其他的为非默认
        /// </summary>
        public void UpdateDefault(QueryPlan queryPlan)
        {
            string sql;
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@dqID", TDbDataType.VarChar, queryPlan.DQID));
            paramList.Add(DB.MakeInParam("@pageID", TDbDataType.VarChar, queryPlan.PageID));
            paramList.Add(DB.MakeInParam("@userId", TDbDataType.VarChar, queryPlan.UserID));
            paramList.Add(DB.MakeInParam("@businessTag", TDbDataType.VarChar, queryPlan.BusinessTag));
            if (queryPlan.PlanRange == PlanRange.Public)
            {
                sql = $@"update {TableName} set IsDefault=0 Where PageID=@pageID
{(string.IsNullOrEmpty(queryPlan.DQID) ? "AND (DQID = '' or DQID is null)" : " and DQID=@dqID ")}
{(string.IsNullOrEmpty(queryPlan.BusinessTag) ? "AND (BusinessTag = '' or BusinessTag is null)" : " and BusinessTag=@businessTag ")}
and PlanRange=0";
            }
            else
            {
                sql = $@"update {TableName} set IsDefault=0 Where PageID=@pageID 
{(string.IsNullOrEmpty(queryPlan.DQID) ? "AND (DQID = '' or DQID is null)" : " and DQID=@dqID ")}
{(string.IsNullOrEmpty(queryPlan.BusinessTag) ? "AND (BusinessTag = '' or BusinessTag is null)" : " and BusinessTag=@businessTag ")}
and  UserID=@userId and PlanRange in (1,2,3)";
            }
            DB.ExecSqlStatement(sql, paramList.ToArray());
        }
        #endregion
        /// <summary>
        /// 删除方案
        /// </summary>
        public void DeletePlan(string contentID)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@contentID", TDbDataType.VarChar, contentID));
            var sql = $"delete from {TableName} Where ContentID=@contentID";
            DB.ExecSqlStatement(sql, paramList.ToArray());
        }
        /// <summary>
        /// 查询方案是否已存在
        /// </summary>
        public QueryPlan GetQueryPlan(string contentID, string userID)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@contentID", TDbDataType.VarChar, contentID));
            paramList.Add(DB.MakeInParam("@userID", TDbDataType.VarChar, userID));
            var sql = string.Format($@"select * from {TableName} where ContentID=@contentID and UserID=@userID");
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                return ConvertToObject(Columns, ds.Tables[0].Rows[0]);
            }
            return null;
        }
        /// <summary>
        /// 删除分享方案
        /// </summary>
        public void DeleteSharePlan(string contentID, string userID)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@contentID", TDbDataType.VarChar, contentID));
            paramList.Add(DB.MakeInParam("@userID", TDbDataType.VarChar, userID));
            var sql = $"delete from {TableName} Where ContentID=@contentID and UserID!=@userID";
            DB.ExecSqlStatement(sql, paramList.ToArray());
        }
        /// <summary>
        /// 从分享方案中删除用户
        /// </summary>
        public void DeleteSharePlanUser(string contentID, string userID)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@contentID", TDbDataType.VarChar, contentID));
            paramList.Add(DB.MakeInParam("@userID", TDbDataType.VarChar, userID));
            var sql = $"delete from {TableName} Where ContentID=@contentID and UserID=@userID";
            DB.ExecSqlStatement(sql, paramList.ToArray());
        }
        /// <summary>
        /// 修改共享方案名称
        /// </summary>
        public void UpdateQueryPlanName(string contentID, string name)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@name", TDbDataType.VarChar, name));
            paramList.Add(DB.MakeInParam("@contentID", TDbDataType.VarChar, contentID));
            var sql = $"update {TableName} set Name=@name Where ContentID=@contentID";
            DB.ExecSqlStatement(sql, paramList.ToArray());
        }
        /// <summary>
        /// 修改预警ID
        /// </summary>
        public void UpdateWaringID(string contentID, string warningID)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@contentID", TDbDataType.VarChar, contentID));
            paramList.Add(DB.MakeInParam("@warningID", TDbDataType.VarChar, warningID));
            var sql = $"update {TableName} set WarningID=@warningID Where ContentID=@contentID;";
            DB.ExecSqlStatement(sql, paramList.ToArray());
        }
        /// <summary>
        /// 保存查询方案顺序
        /// </summary>
        public void UpdateOrder(List<QueryPlan> queryPlans)
        {
            int i = 0;
            foreach (var item in queryPlans)
            {
                if (item.PlanRange == PlanRange.Public)
                    item.PlanOrder = i;
                else
                    item.PlanOrder = 100 + i;
                List<IDbDataParameter> paramList = new List<IDbDataParameter>
                {
                    DB.MakeInParam("@id", TDbDataType.VarChar, item.ID),
                    DB.MakeInParam("@PlanOrder", item.PlanOrder),
                };
                string sql = $"update {TableName} set PlanOrder=@PlanOrder Where ID=@id;";
                DB.ExecSqlStatement(sql, paramList.ToArray());
                i++;
            }
        }
        /// <summary>
        /// 获取分享人员
        /// </summary>
        public List<QueryPlanUser> GetShareUserName(string contentID)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@contentID", TDbDataType.VarChar, contentID));
            var sql = string.Format($@"select UserID,UserName from fas_queryplan where ContentID=@contentID and PlanRange={(int)PlanRange.Shared} ");
            List<QueryPlanUser> shareUsers = new List<QueryPlanUser>();
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var shareUser = new QueryPlanUser();
                    shareUser.UserID = ds.Tables[0].Rows[i]["UserID"].ToString();
                    shareUser.UserName = ds.Tables[0].Rows[i]["UserName"].ToString();
                    shareUsers.Add(shareUser);
                }
            }
            return shareUsers;
        }
        /// <summary>
        /// 获取方案最大排序
        /// </summary>
        public int GetMaxOrder(QueryPlan queryPlan)
        {
            int maxOrder = 10000;
            var result = new List<QueryPlan>();
            List<IDbDataParameter> paramList = new List<IDbDataParameter>
            {
                DB.MakeInParam("@pageID", TDbDataType.VarChar, queryPlan.PageID),
                DB.MakeInParam("@DQID", TDbDataType.VarChar, queryPlan.DQID),
                DB.MakeInParam("@userID", TDbDataType.VarChar, queryPlan.UserID),
                DB.MakeInParam("@BusinessTag", TDbDataType.VarChar, queryPlan.BusinessTag)
            };
            var sql = $@"select ID,Name,PlanOrder from {TableName} where PageID=@pageID 
{(string.IsNullOrEmpty(queryPlan.DQID) ? "AND (DQID = '' or DQID is null)" : " and DQID=@DQID ")}
{(string.IsNullOrEmpty(queryPlan.BusinessTag) ? "AND (BusinessTag = '' or BusinessTag is null)" : " and BusinessTag=@BusinessTag ")}
";
            if (queryPlan.PlanRange == PlanRange.Public)
                sql += " and PlanRange=0";
            else
                sql += " and UserID=@userID and PlanRange in (1,2,3)";
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    var data = new QueryPlan();
                    data.ID = Convert.ToString(row["ID"]);
                    data.Name = Convert.ToString(row["Name"]);
                    data.PlanOrder = Convert.ToInt32(row["PlanOrder"]);
                    result.Add(data);
                }
                if (result.Any(t => t.Name == queryPlan.Name))
                {
                    throw new Exception($"{TermService.Current.GetText("T_FAS_fasr_Base_1823931117", "方案名称不能重复")}");
                }
                maxOrder = result.Max(t => t.PlanOrder);
            }
            return maxOrder + 1;
        }
        /// <summary>
        /// 获取查询方案列表
        /// </summary>
        /// <param name="pageID"></param>
        /// <param name="DQID"></param>
        /// <returns></returns>
        public QueryPlan GetSystemPlan(QueryPlanFilter queryPlanFilter)
        {
            List<IDbDataParameter> paramList = new List<IDbDataParameter>
            {
                DB.MakeInParam("@PageID", TDbDataType.VarChar, queryPlanFilter.PageID),
                DB.MakeInParam("@DQID", TDbDataType.VarChar, queryPlanFilter.DQID),
                DB.MakeInParam("@BusinessTag", TDbDataType.VarChar, queryPlanFilter.BusinessTag)
            };
            var sql = $@"
SELECT
  *
FROM
  {TableName} plan
WHERE
  PageID = @PageID
{(string.IsNullOrEmpty(queryPlanFilter.DQID) ? "AND (DQID = '' or DQID is null)" : "AND DQID = @DQID")}
{(string.IsNullOrEmpty(queryPlanFilter.BusinessTag) ? "AND (BusinessTag = '' or BusinessTag is null)" : "AND BusinessTag = @BusinessTag")}
  AND PlanRange = 0
  AND IsSystem = 1";
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    return ConvertToObject(Columns, ds.Tables[0].Rows[0]);
                }
            }
            return null;
        }
        /// <summary>
        /// 获取查询方案列表
        /// </summary>
        /// <param name="pageID"></param>
        /// <param name="DQID"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public List<QueryPlan> GetQueryPlanList(string pageID, string DQID, string userID)
        {
            var result = new List<QueryPlan>();
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@pageID", TDbDataType.VarChar, pageID));
            paramList.Add(DB.MakeInParam("@DQID", TDbDataType.VarChar, DQID));
            paramList.Add(DB.MakeInParam("@userID", TDbDataType.VarChar, userID));
            var sql = $@"SELECT
  plan.ID,
  plan.DQID,
  plan.PageID,
  plan.Name,
  PlanRange,
  plan.DefaultView,
  plan.IsDefault,
  plan.UserID,
  plan.UserName,
  plan.SharedBy,
  plan.PlanOrder,
  ContentID,
  content.UseColumnContent,
  content.FilterContent,
  content.ColumnContent,
  content.SortContent,
  content.CrossColumn
FROM
  fas_queryplan plan
  JOIN FAS_QueryPlanContent content ON plan.ContentID = content.ID
WHERE
  plan.PageID = @pageID
{(string.IsNullOrEmpty(DQID) ? "AND (DQID = '' or DQID is null)" : " AND plan.DQID = @DQID ")}
  AND (
    plan.UserID = @userID
    OR PlanRange = 0
  )
ORDER BY
  plan.PlanRange,
  PlanOrder,
  Name";
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    var data = new QueryPlan();
                    data.ID = Convert.ToString(row["ID"]);
                    data.DQID = Convert.ToString(row["DQID"]);
                    data.PageID = Convert.ToString(row["PageID"]);
                    data.Name = Convert.ToString(row["Name"]);
                    if (row["PlanRange"] != DBNull.Value)
                        data.PlanRange = (PlanRange)Enum.Parse(typeof(PlanRange), Convert.ToString(row["PlanRange"]));
                    else
                        data.PlanRange = PlanRange.Private;
                    if (row["DefaultView"] != DBNull.Value)
                        data.DefaultView = (ViewType)Enum.Parse(typeof(ViewType), Convert.ToString(row["DefaultView"]));
                    if (row["IsDefault"] != DBNull.Value)
                        data.IsDefault = Convert.ToBoolean(row["IsDefault"]);
                    data.UserID = Convert.ToString(row["UserID"]);
                    data.UserName = Convert.ToString(row["UserName"]);
                    data.SharedBy = Convert.ToString(row["SharedBy"]);
                    if (data.PlanRange == PlanRange.Public)
                        data.PlanOrder = i;
                    else
                        data.PlanOrder = 100 + i;
                    data.ContentID = Convert.ToString(row["ContentID"]);
                    if (row["UseColumnContent"] != DBNull.Value)
                        data.UseColumnContent = Convert.ToBoolean(row["UseColumnContent"]);
                    data.FilterContent = Convert.ToString(row["FilterContent"]);
                    data.ColumnContent = Convert.ToString(row["ColumnContent"]);
                    data.SortContent = Convert.ToString(row["SortContent"]);
                    data.CrossColumn = Convert.ToString(row["CrossColumn"]);
                    result.Add(data);
                }
            }
            string UserName = UserUtil.GetCurrentUserName();
            int hasPublic = result.Count(t => t.PlanRange == PlanRange.Public && t.IsDefault);
            if (hasPublic == 0)
            {
                var content = new QueryPlanContent
                {
                    LastModifyTime = DateTime.Now,
                    LastModifier = UserName,
                    ID = Guid.NewGuid().ToString(),
                    FilterContent = "{\"ElementType\":\"Group\",\"Filters\":[]}",
                    SortContent = "[]",
                };
                var detail = new QueryPlanDetail
                {
                    LastModifyTime = DateTime.Now,
                    LastModifier = UserName,
                    ID = content.ID,
                    ListViewSet = JsonConvert.SerializeObject(new { pageSize = "10", showAutoFilterRow = false })
                };
                QueryPlan queryPlan = new QueryPlan
                {
                    LastModifyTime = DateTime.Now,
                    LastModifier = UserName,
                    UserID = userID,
                    ID = Guid.NewGuid().ToString(),
                    Name = "全部",
                    PlanOrder = -1,
                    FilterContent = "{\"ElementType\":\"Group\",\"Filters\":[]}",
                    SortContent = "[]",
                    DQID = DQID,
                    PageID = pageID,
                    IsDefault = true,
                    IsSystem = true,
                    PlanRange = PlanRange.Public,
                    ContentID = content.ID,
                    ListViewSet = detail.ListViewSet
                };
                new QueryPlanContentDao().Add(new List<object> { content });
                new QueryPlanDetailDao().Add(new List<object> { detail });
                base.Add(new List<object> { queryPlan });
                result.Add(queryPlan);
            }
            return result.OrderByDescending(t => t.TopTime).ThenBy(t => t.PlanOrder).ThenBy(t => t.Name).ToList();
        }
        /// <summary>
        /// 新版获取查询方案列表
        /// </summary>
        /// <param name="pageID"></param>
        /// <param name="DQID"></param>
        /// <param name="userID"></param>
        /// <param name="sortCode"></param>
        /// <returns></returns>
        public List<QueryPlan> GetQueryPlanListV2(QueryPlanFilter queryPlanFilter)
        {
            var result = new List<QueryPlan>();
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@PageID", TDbDataType.VarChar, queryPlanFilter.PageID));
            paramList.Add(DB.MakeInParam("@DQID", TDbDataType.VarChar, queryPlanFilter.DQID));
            paramList.Add(DB.MakeInParam("@BusinessTag", TDbDataType.VarChar, queryPlanFilter.BusinessTag));
            paramList.Add(DB.MakeInParam("@UserID", TDbDataType.VarChar, queryPlanFilter.UserID));
            var sql = $@"
SELECT
  plan.ID,
  plan.DQID,
  plan.PageID,
  plan.Name,
  plan.PlanRange,
  plan.DefaultView,
  plan.IsSystem,
  plan.UserID,
  plan.UserName,
  plan.BusinessTag,
  plan.SharedBy,
  plan.PlanOrder,
  plan.ContentID,
  plan.PlanType,
  detail.FilterContent,
  detail.FilterShow,
  detail.ListViewSet,
  detail.ChartViewSet,
  detail.PivotViewSet,
  detail.TreeViewSet,
  detail.CardViewSet,
  detail.WarningID,
  detail.PortalId,
  detail.DefaultPortalId,
  detail.PortalFilterContent,
  plandefault.IsDefault,
  planuser.TopTime
FROM
  fas_queryplan plan
  JOIN FAS_QueryPlanDetail detail ON plan.ContentID = detail.ID
  LEFT JOIN FAS_QueryPlanUser planuser ON plan.ID = planuser.PlanID AND planuser.UserID = @UserID
  LEFT JOIN FAS_QueryPlanDefault plandefault ON plan.ID = plandefault.PlanID and plan.PageID =plandefault.PageID AND plandefault.UserID = @UserID
WHERE
  plan.PageID = @PageID
  {(string.IsNullOrEmpty(queryPlanFilter.DQID) ? "AND (plan.DQID = '' or plan.DQID is null)" : "AND plan.DQID = @DQID")}
  {(string.IsNullOrEmpty(queryPlanFilter.BusinessTag) ? "AND (plan.BusinessTag = '' or plan.BusinessTag is null)" : "AND plan.BusinessTag = @BusinessTag")}
  AND (
    plan.UserID = @UserID
    OR PlanRange = 0
  )
ORDER BY
  planuser.TopTime desc,
  plan.PlanOrder,
  plan.Name";
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    var data = new QueryPlan();
                    data.ID = Convert.ToString(row["ID"]);
                    data.DQID = Convert.ToString(row["DQID"]);
                    data.PageID = Convert.ToString(row["PageID"]);
                    data.WarningID = Convert.ToString(row["WarningID"]);
                    data.PortalId = Convert.ToString(row["PortalId"]);
                    data.DefaultPortalId = Convert.ToString(row["DefaultPortalId"]);
                    data.BusinessTag = Convert.ToString(row["BusinessTag"]);
                    data.PortalFilterContent = Convert.ToString(row["PortalFilterContent"]);
                    data.Name = Convert.ToString(row["Name"]);
                    if (row["PlanRange"] != DBNull.Value)
                        data.PlanRange = (PlanRange)Enum.Parse(typeof(PlanRange), Convert.ToString(row["PlanRange"]));
                    else
                        data.PlanRange = PlanRange.Private;
                    if (row["DefaultView"] != DBNull.Value)
                        data.DefaultView = (ViewType)Enum.Parse(typeof(ViewType), Convert.ToString(row["DefaultView"]));
                    if (row[nameof(QueryPlan.PlanType)] != DBNull.Value)
                        data.PlanType = (PlanType)Enum.Parse(typeof(PlanType), Convert.ToString(row["PlanType"]));
                    if (row["IsDefault"] != DBNull.Value)
                        data.IsDefault = Convert.ToBoolean(row["IsDefault"]);
                    if (row["IsSystem"] != DBNull.Value)
                        data.IsSystem = Convert.ToBoolean(row["IsSystem"]);
                    if (row["TopTime"] != DBNull.Value)
                        data.TopTime = DateTime.Parse(Convert.ToString(row["TopTime"]));
                    data.UserID = Convert.ToString(row["UserID"]);
                    data.UserName = Convert.ToString(row["UserName"]);
                    data.SharedBy = Convert.ToString(row["SharedBy"]);
                    if (data.PlanRange == PlanRange.Public)
                        data.PlanOrder = i;
                    else
                        data.PlanOrder = 100 + i;
                    data.ContentID = Convert.ToString(row["ContentID"]);
                    data.FilterContent = Convert.ToString(row["FilterContent"]);
                    data.FilterShow = Convert.ToString(row["FilterShow"]);
                    data.ListViewSet = Convert.ToString(row["ListViewSet"]);
                    data.ChartViewSet = Convert.ToString(row["ChartViewSet"]);
                    data.PivotViewSet = Convert.ToString(row["PivotViewSet"]);
                    data.TreeViewSet = Convert.ToString(row["TreeViewSet"]);
                    data.CardViewSet = Convert.ToString(row["CardViewSet"]);
                    result.Add(data);
                }
            }
            return GetQueryPlanResult(queryPlanFilter, result, true, true);
        }

        private List<QueryPlan> GetQueryPlanResult(QueryPlanFilter queryPlanFilter, List<QueryPlan> result, bool hasDefault, bool needShareUser)
        {
            string UserName = UserUtil.GetCurrentUserName();
            int hasSysDefault = result.Count(t => t.IsSystem);
            if (hasSysDefault == 0)
            {
                var sysqueryPlan = CreateSysQueryplan(queryPlanFilter);
                result.Add(sysqueryPlan);
            }
            foreach (var item in result)
            {
                HandlePlanInfo(item, queryPlanFilter.UserID, queryPlanFilter.HasModifyAuth, needShareUser);
                if (item.IsSystem && !hasDefault)
                {
                    GetQueryPlanDetail(item);
                }
            }
            switch (queryPlanFilter.SortCode)
            {
                case "plan.Name desc":
                    return result.OrderByDescending(t => t.TopTime).ThenByDescending(t => t.Name).ToList();
                case "plan.Name asc":
                    return result.OrderByDescending(t => t.TopTime).ThenBy(t => t.Name).ToList();
                default:
                    return result.OrderByDescending(t => t.TopTime).ThenBy(t => t.PlanOrder).ToList();
            }
        }

        public QueryPlan CreateSysQueryplan(QueryPlanFilter queryPlanFilter)
        {
            //using (ICacheClient client = CacheService.GetInstance("DefaultPool").GetClient())
            {
              //  using (var _lock = DataLockService.AddLock(client, $"DataLock{queryPlanFilter.PageID}", TimeSpan.FromSeconds(10)))
                {
                    var sysqueryPlan = GetSystemPlan(queryPlanFilter);
                    if (sysqueryPlan == null)
                    {
                        QueryPlanDetail content;
                        QueryPlan queryPlan;
                        CreateDefaultPlan(queryPlanFilter, out content, out queryPlan);
                        using (TransactionScope scope = new TransactionScope())
                        {
                            new QueryPlanDetailDao().Add(new List<object> { content });
                            base.Add(new List<object> { queryPlan });
                            scope.Complete();
                            return queryPlan;
                        }
                    }
                    else
                    {
                        return GetSystemPlan(queryPlanFilter);
                    }
                }
            }
        }

        /// <summary>
        /// 处理方案分享明细
        /// </summary>
        public void HandlePlanInfo(QueryPlan queryPlan, string userId, bool hasModifyAuth, bool needShareUser)
        {
            switch (queryPlan.PlanRange)
            {
                case PlanRange.Private:
                case PlanRange.Share:
                case PlanRange.Shared:
                    queryPlan.IsSystem = false;
                    if (queryPlan.PlanRange == PlanRange.Shared || userId != queryPlan.UserID)
                        queryPlan.IsAuth = false;
                    else
                        queryPlan.IsAuth = true;
                    if (needShareUser && (queryPlan.PlanRange == PlanRange.Share || queryPlan.PlanRange == PlanRange.Shared))
                        queryPlan.ShareUsers = GetShareUserName(queryPlan.ContentID);//获取分享人员
                    break;
                case PlanRange.Public:
                    queryPlan.IsAuth = hasModifyAuth;
                    break;
            }
            if (queryPlan.Name == "全部")
            {
                queryPlan.Name = TermService.Current.GetText("T_FAS_fasr_Base_63485579", "全部");
            }
        }

        /// <summary>
        /// 方案获取明细
        /// </summary>
        /// <param name="queryPlan"></param>
        public void GetQueryPlanDetail(QueryPlan queryPlan)
        {
            QueryPlanDetail queryPlanDetail = new QueryPlanDetailDao().GetObject(queryPlan.ContentID);
            if (queryPlanDetail != null)
            {
                queryPlan.FilterContent = queryPlanDetail.FilterContent;
                queryPlan.FilterShow = queryPlanDetail.FilterShow;
                queryPlan.ListViewSet = queryPlanDetail.ListViewSet;
                queryPlan.PivotViewSet = queryPlanDetail.PivotViewSet;
                queryPlan.TreeViewSet = queryPlanDetail.TreeViewSet;
                queryPlan.ChartViewSet = queryPlanDetail.ChartViewSet;
                queryPlan.CardViewSet = queryPlanDetail.CardViewSet;
                queryPlan.WarningID = queryPlanDetail.WarningID;
                queryPlan.PortalFilterContent = queryPlanDetail.PortalFilterContent;
                queryPlan.PortalId = queryPlanDetail.PortalId;
                queryPlan.DefaultPortalId = queryPlanDetail.DefaultPortalId;
            }
        }
        /// <summary>
        /// 获取查询方案列表不带明细
        /// </summary>
        /// <returns></returns>
        public List<QueryPlan> GetQueryPlanListV3(QueryPlanFilter queryPlanFilter)
        {
            var result = new List<QueryPlan>();
            List<IDbDataParameter> paramList = new List<IDbDataParameter>();
            paramList.Add(DB.MakeInParam("@PageID", TDbDataType.VarChar, queryPlanFilter.PageID));
            paramList.Add(DB.MakeInParam("@DQID", TDbDataType.VarChar, queryPlanFilter.DQID));
            paramList.Add(DB.MakeInParam("@BusinessTag", TDbDataType.VarChar, queryPlanFilter.BusinessTag));
            paramList.Add(DB.MakeInParam("@UserID", TDbDataType.VarChar, queryPlanFilter.UserID));
            var sql = $@"
SELECT
  plan.ID,
  plan.DQID,
  plan.PageID,
  plan.Name,
  plan.PlanRange,
  plan.DefaultView,
  plan.IsSystem,
  plan.UserID,
  plan.UserName,
  plan.BusinessTag,
  plan.SharedBy,
  plan.PlanOrder,
  plan.ContentID,
  plan.PlanType,
  detail.WarningID,
  detail.PortalId,
  detail.DefaultPortalId,
  plandefault.IsDefault,
  planuser.TopTime
FROM
  fas_queryplan plan
  JOIN FAS_QueryPlanDetail detail ON plan.ContentID = detail.ID
  LEFT JOIN FAS_QueryPlanUser planuser ON plan.ID = planuser.PlanID  AND planuser.UserID = @UserID
  LEFT JOIN FAS_QueryPlanDefault plandefault ON plan.ID = plandefault.PlanID AND plan.PageID =plandefault.PageID  AND plandefault.UserID = @UserID
WHERE
  plan.PageID = @PageID
  {(string.IsNullOrEmpty(queryPlanFilter.DQID) ? "AND (plan.DQID = '' or plan.DQID is null)" : "AND plan.DQID = @DQID")}
  {(string.IsNullOrEmpty(queryPlanFilter.BusinessTag) ? "AND (plan.BusinessTag = '' or plan.BusinessTag is null)" : "AND plan.BusinessTag = @BusinessTag")}
  AND (
    plan.UserID = @UserID
    OR PlanRange = 0
  )
ORDER BY
  planuser.TopTime desc,
  plan.PlanOrder,
  plan.Name";
            var ds = DB.ExecuteDataSet(sql, paramList.ToArray());
            bool hasDefault = false;
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    var data = new QueryPlan();
                    data.ID = Convert.ToString(row["ID"]);
                    data.DQID = Convert.ToString(row["DQID"]);
                    data.PageID = Convert.ToString(row["PageID"]);
                    data.WarningID = Convert.ToString(row["WarningID"]);
                    data.PortalId = Convert.ToString(row["PortalId"]);
                    data.DefaultPortalId = Convert.ToString(row["DefaultPortalId"]);
                    data.BusinessTag = Convert.ToString(row["BusinessTag"]);
                    data.ContentID = Convert.ToString(row["ContentID"]);
                    data.Name = Convert.ToString(row["Name"]);
                    if (row["PlanRange"] != DBNull.Value)
                        data.PlanRange = (PlanRange)Enum.Parse(typeof(PlanRange), Convert.ToString(row["PlanRange"]));
                    else
                        data.PlanRange = PlanRange.Private;
                    if (row["DefaultView"] != DBNull.Value)
                        data.DefaultView = (ViewType)Enum.Parse(typeof(ViewType), Convert.ToString(row["DefaultView"]));
                    if (row[nameof(QueryPlan.PlanType)] != DBNull.Value)
                        data.PlanType = (PlanType)Enum.Parse(typeof(PlanType), Convert.ToString(row["PlanType"]));
                    if (row["IsDefault"] != DBNull.Value)
                        data.IsDefault = Convert.ToBoolean(row["IsDefault"]);
                    if (data.IsDefault)
                    {
                        hasDefault = true;
                        GetQueryPlanDetail(data);
                    }
                    if (row["IsSystem"] != DBNull.Value)
                        data.IsSystem = Convert.ToBoolean(row["IsSystem"]);
                    if (row["TopTime"] != DBNull.Value)
                        data.TopTime = DateTime.Parse(Convert.ToString(row["TopTime"]));
                    data.UserID = Convert.ToString(row["UserID"]);
                    data.UserName = Convert.ToString(row["UserName"]);
                    data.SharedBy = Convert.ToString(row["SharedBy"]);
                    if (data.PlanRange == PlanRange.Public)
                        data.PlanOrder = i;
                    else
                        data.PlanOrder = 100 + i;
                    data.ContentID = Convert.ToString(row["ContentID"]);
                    result.Add(data);
                }
            }
            return GetQueryPlanResult(queryPlanFilter, result, hasDefault, false);
        }
        /// <summary>
        /// 创建默认方案
        /// </summary>
        /// <param name="pageID"></param>
        /// <param name="dqId"></param>
        /// <param name="userID"></param>
        /// <param name="UserName"></param>
        /// <param name="content"></param>
        /// <param name="queryPlan"></param>
        private static void CreateDefaultPlan(QueryPlanFilter queryPlanFilter, out QueryPlanDetail content, out QueryPlan queryPlan)
        {
            //dqid为空暂时认为是门户方案
            if (string.IsNullOrEmpty(queryPlanFilter.DQID))
            {
                var service = PlanServiceCache.GetInstance().GetIQueryPlanServices("Portal");
                queryPlan = service.GetDefaultPlan(queryPlanFilter.PageID, queryPlanFilter.DQID, out content);
                queryPlan.BusinessTag = queryPlanFilter.BusinessTag;
            }
            else
            {
                content = new QueryPlanDetail
                {
                    LastModifyTime = DateTime.Now,
                    LastModifier = queryPlanFilter.UserName,
                    ID = Guid.NewGuid().ToString(),
                    FilterContent = "{\"ElementType\":\"Group\",\"Filters\":[]}",
                    FilterShow = "{\"FilterModel\":\"Classic\",\"FilterGroups\":[]}",
                    ListViewSet = JsonConvert.SerializeObject(new { pageSize = "10", showAutoFilterRow = false })
                };
                queryPlan = new QueryPlan
                {
                    LastModifyTime = DateTime.Now,
                    LastModifier = queryPlanFilter.UserName,
                    UserID = queryPlanFilter.UserID,
                    ID = Guid.NewGuid().ToString(),
                    Name = "全部",
                    PlanOrder = -1,
                    PageID = queryPlanFilter.PageID,
                    DQID = queryPlanFilter.DQID,
                    BusinessTag = queryPlanFilter.BusinessTag,
                    IsDefault = true,
                    IsSystem = true,
                    PlanRange = PlanRange.Public,
                    ContentID = content.ID,
                    FilterContent = "{\"ElementType\":\"Group\",\"Filters\":[]}",
                    FilterShow = "{\"FilterModel\":\"Classic\",\"FilterGroups\":[]}",
                    ListViewSet = JsonConvert.SerializeObject(new { pageSize = "10", showAutoFilterRow = false })
                };
            }
        }
    }
}
